/*
 *  Copyright (C) 2010 Joaquin
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * CCGUI.java
 *
 * Created on 31/08/2010, 14:55:27
 */
package jogamesuite;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.ListDataListener;
import jogamesuite.lib.*;

/**
 *
 * @author Joaquin
 */
public class CCGUI extends javax.swing.JFrame {

    /** Creates new form CCGUI */
    public CCGUI() {
        initComponents();
        setUpListeners();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.JPanel inputPanel = new javax.swing.JPanel();
        javax.swing.JLabel jLabel1 = new javax.swing.JLabel();
        metalRatioField = new javax.swing.JTextField();
        cristalRatioField = new javax.swing.JTextField();
        deuteriumRatioField = new javax.swing.JTextField();
        javax.swing.JLabel jLabel2 = new javax.swing.JLabel();
        javax.swing.JLabel jLabel3 = new javax.swing.JLabel();
        javax.swing.JLabel jLabel4 = new javax.swing.JLabel();
        resource2TradeBox = new javax.swing.JComboBox();
        javax.swing.JLabel jLabel5 = new javax.swing.JLabel();
        amount2TradeField = new javax.swing.JTextField();
        javax.swing.JPanel tradeTypePanel = new javax.swing.JPanel();
        tradeTypeBox = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        fixedResourceBox = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        amount2FixField = new javax.swing.JTextField();
        resultTrade = new javax.swing.JPanel();
        javax.swing.JLabel jLabel10 = new javax.swing.JLabel();
        deuteriumOut = new javax.swing.JTextField();
        javax.swing.JLabel jLabel9 = new javax.swing.JLabel();
        cristalOut = new javax.swing.JTextField();
        javax.swing.JLabel jLabel8 = new javax.swing.JLabel();
        metalOut = new javax.swing.JTextField();
        calcButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        javax.swing.JPanel textOutput = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        javax.swing.JPanel tradeSummary = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        summaryOutput = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JOgame Calculadora de Comercio"); // NOI18N
        setLocationByPlatform(true);
        setResizable(false);

        jLabel1.setText("Ratio de comercio (MxCxD)"); // NOI18N

        metalRatioField.setColumns(3);
        metalRatioField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        metalRatioField.setText("3"); // NOI18N

        cristalRatioField.setColumns(3);
        cristalRatioField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        cristalRatioField.setText("2"); // NOI18N

        deuteriumRatioField.setColumns(3);
        deuteriumRatioField.setEditable(false);
        deuteriumRatioField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        deuteriumRatioField.setText("1"); // NOI18N
        deuteriumRatioField.setFocusable(false);

        jLabel2.setText("x"); // NOI18N

        jLabel3.setText("x"); // NOI18N

        jLabel4.setText("Recurso a comerciar:"); // NOI18N

        resource2TradeBox.setModel(new DefaultComboBoxModel(Resource.values()));

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel5.setText("Cantidad :"); // NOI18N

        amount2TradeField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        amount2TradeField.setText("0");
        amount2TradeField.setAction(new CalculateAction());

        javax.swing.GroupLayout inputPanelLayout = new javax.swing.GroupLayout(inputPanel);
        inputPanel.setLayout(inputPanelLayout);
        inputPanelLayout.setHorizontalGroup(
            inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(inputPanelLayout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(metalRatioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cristalRatioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deuteriumRatioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(inputPanelLayout.createSequentialGroup()
                .addGroup(inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(resource2TradeBox, 0, 224, Short.MAX_VALUE)
                    .addComponent(amount2TradeField, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)))
        );

        inputPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel4, jLabel5});

        inputPanelLayout.setVerticalGroup(
            inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(inputPanelLayout.createSequentialGroup()
                .addGroup(inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(metalRatioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cristalRatioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(deuteriumRatioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(resource2TradeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(inputPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(amount2TradeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        tradeTypePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Tipo de Comercio"));

        tradeTypeBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Sólo un recurso", "Mezcla de recursos" }));

        jLabel7.setText("Fijar recurso:");

        fixedResourceBox.setModel(new DefaultComboBoxModel(Resource.values()));
        fixedResourceBox.setEnabled(false);

        jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel11.setText("Cantidad:");

        amount2FixField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        amount2FixField.setText("0");
        amount2FixField.setAction(new CalculateAction());
        amount2FixField.setEnabled(false);

        javax.swing.GroupLayout tradeTypePanelLayout = new javax.swing.GroupLayout(tradeTypePanel);
        tradeTypePanel.setLayout(tradeTypePanelLayout);
        tradeTypePanelLayout.setHorizontalGroup(
            tradeTypePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tradeTypePanelLayout.createSequentialGroup()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fixedResourceBox, 0, 259, Short.MAX_VALUE))
            .addComponent(tradeTypeBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 344, Short.MAX_VALUE)
            .addGroup(tradeTypePanelLayout.createSequentialGroup()
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(amount2FixField, javax.swing.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE))
        );

        tradeTypePanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel11, jLabel7});

        tradeTypePanelLayout.setVerticalGroup(
            tradeTypePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tradeTypePanelLayout.createSequentialGroup()
                .addComponent(tradeTypeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tradeTypePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fixedResourceBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tradeTypePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(amount2FixField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)))
        );

        resultTrade.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultados"));

        jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel10.setLabelFor(deuteriumOut);
        jLabel10.setText("Deuterio:"); // NOI18N

        deuteriumOut.setColumns(10);
        deuteriumOut.setEditable(false);
        deuteriumOut.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        deuteriumOut.setFocusable(false);

        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel9.setLabelFor(cristalOut);
        jLabel9.setText("Cristal:"); // NOI18N

        cristalOut.setColumns(10);
        cristalOut.setEditable(false);
        cristalOut.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        cristalOut.setFocusable(false);

        jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel8.setLabelFor(metalOut);
        jLabel8.setText("Metal:"); // NOI18N

        metalOut.setColumns(10);
        metalOut.setEditable(false);
        metalOut.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        metalOut.setFocusable(false);

        javax.swing.GroupLayout resultTradeLayout = new javax.swing.GroupLayout(resultTrade);
        resultTrade.setLayout(resultTradeLayout);
        resultTradeLayout.setHorizontalGroup(
            resultTradeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(resultTradeLayout.createSequentialGroup()
                .addGroup(resultTradeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel10)
                    .addComponent(jLabel9)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(resultTradeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(metalOut, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                    .addComponent(cristalOut, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                    .addComponent(deuteriumOut, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)))
        );

        resultTradeLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel10, jLabel8, jLabel9});

        resultTradeLayout.setVerticalGroup(
            resultTradeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(resultTradeLayout.createSequentialGroup()
                .addGroup(resultTradeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(deuteriumOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(resultTradeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cristalOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(resultTradeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(metalOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8)))
        );

        calcButton.setAction(new CalculateAction());
        calcButton.setText("Calcular"); // NOI18N

        jButton1.setAction(new CleanAction());
        jButton1.setText("Limpiar");

        textOutput.setBorder(javax.swing.BorderFactory.createTitledBorder("Texto para foros"));

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout textOutputLayout = new javax.swing.GroupLayout(textOutput);
        textOutput.setLayout(textOutputLayout);
        textOutputLayout.setHorizontalGroup(
            textOutputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(textOutputLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)
                .addContainerGap())
        );
        textOutputLayout.setVerticalGroup(
            textOutputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(textOutputLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                .addContainerGap())
        );

        tradeSummary.setBorder(javax.swing.BorderFactory.createTitledBorder("Resumen de la Transacción"));

        summaryOutput.setBorder(null);
        summaryOutput.setEditable(false);
        jScrollPane2.setViewportView(summaryOutput);

        javax.swing.GroupLayout tradeSummaryLayout = new javax.swing.GroupLayout(tradeSummary);
        tradeSummary.setLayout(tradeSummaryLayout);
        tradeSummaryLayout.setHorizontalGroup(
            tradeSummaryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
        );
        tradeSummaryLayout.setVerticalGroup(
            tradeSummaryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(calcButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(tradeTypePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(inputPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textOutput, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tradeSummary, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(resultTrade, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {inputPanel, textOutput, tradeTypePanel});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {resultTrade, tradeSummary});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(resultTrade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tradeSummary, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(inputPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tradeTypePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(calcButton)
                            .addComponent(jButton1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textOutput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            // Set System L&F
            UIManager.setLookAndFeel(
                    UIManager.getSystemLookAndFeelClassName());
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CCGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField amount2FixField;
    private javax.swing.JTextField amount2TradeField;
    private javax.swing.JButton calcButton;
    private javax.swing.JTextField cristalOut;
    private javax.swing.JTextField cristalRatioField;
    private javax.swing.JTextField deuteriumOut;
    private javax.swing.JTextField deuteriumRatioField;
    private javax.swing.JComboBox fixedResourceBox;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField metalOut;
    private javax.swing.JTextField metalRatioField;
    private javax.swing.JComboBox resource2TradeBox;
    private javax.swing.JPanel resultTrade;
    private javax.swing.JTextPane summaryOutput;
    private javax.swing.JComboBox tradeTypeBox;
    // End of variables declaration//GEN-END:variables
    private int tradeType = 0;
    private Resource fixedResource = Resource.METAL;
    private Resource res2trade = Resource.METAL;

    public Resource getFixedResource() {
        return fixedResource;
    }

    private void setFixedResource(Resource fixedResource) {
        this.fixedResource = fixedResource;
    }

    public Resource getRes2trade() {
        return res2trade;
    }

    private void setRes2trade(Resource res2trade) {
        this.res2trade = res2trade;
    }

    /**
     * Agrega los escuchas de eventos para los JComboBox y Verificadores para
     * los Campos de texto
     */
    private void setUpListeners() {
        final JComboBox[] boxes = {tradeTypeBox, resource2TradeBox, fixedResourceBox};
        addComboBoxListener2List(new TradeTypeListener(), boxes);
        final AmountVerifier tradeInVerifier = new AmountVerifier(Long.MAX_VALUE, 0, 0);
        addVerifier2List(tradeInVerifier, amount2TradeField, amount2FixField);
        metalRatioField.setInputVerifier(new RatioVerifier(5, 2));
        cristalRatioField.setInputVerifier(new RatioVerifier(3, 1));
        deuteriumRatioField.setInputVerifier(new RatioVerifier(1, 1));
    }

    private void addComboBoxListener2List(ActionListener listener, JComboBox... boxes) {
        for (JComboBox jComboBox : boxes) {
            jComboBox.addActionListener(listener);
        }
    }

    private void addVerifier2List(InputVerifier verifier, JTextField... fields) {
        for (JTextField jTextField : fields) {
            jTextField.setInputVerifier(verifier);
        }
    }

    public int getTradeType() {
        return tradeType;
    }

    private void setTradeType(int tradeType) {
        this.tradeType = tradeType;
    }

    private interface TradeTypeConstants {

        final int ONE_RESOURCE_TRADE_TYPE = 0;
        final int FIXED_RESOURCE_TRADE_TYPE = 1;
    }

    /**
     * Escucha para todos los JComboBox, según sea el que cambie actualiza el
     * GUI y los parámetros de transacción
     */
    private class TradeTypeListener implements ActionListener, TradeTypeConstants {

        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() instanceof JComboBox) {
                JComboBox jComboBox = (JComboBox) ae.getSource();
                if (jComboBox.equals(tradeTypeBox)) {
                    updateTradeType();
                    updateFixerBox();
                } else if (jComboBox.equals(fixedResourceBox)) {
                    setFixedResource((Resource) fixedResourceBox.getSelectedItem());//TODO Handler for fixedResourceBox
                } else if (jComboBox.equals(resource2TradeBox)) {
                    setRes2trade((Resource) resource2TradeBox.getSelectedItem());
                    updateFixerBox();
                }
            }
        }

        /**
         * Updates Trade Type parameters and GUI
         */
        private void updateTradeType() {
            int tradeType = tradeTypeBox.getSelectedIndex();
            boolean enable = false;
            switch (tradeType) {
                case ONE_RESOURCE_TRADE_TYPE:
                    enable = false;
                    break;
                case FIXED_RESOURCE_TRADE_TYPE:
                    enable = true;
                    break;
            }
            enableComponents(enable, fixedResourceBox, amount2FixField);
            setTradeType(tradeType);
        }

        /**
         * Enables specified JComponents
         * @param components
         */
        private void enableComponents(boolean enabled, JComponent... components) {
            for (JComponent jComponent : components) {
                jComponent.setEnabled(enabled);
            }
        }

        /*
         * Updates Fixer JComboBox Options
         */
        private void updateFixerBox() {
            EnumSet<Resource> res2Fix = EnumSet.complementOf(EnumSet.of(res2trade));
            fixedResourceBox.setModel(new DefaultComboBoxModel(res2Fix.toArray()));
        }
    }

    /**
     * Action that calculates the entire transaction based on the parameters on screen.
     */
    private class CalculateAction extends AbstractAction implements TradeTypeConstants {

        // Trade parameters
        private DecimalFormat intFormat = (DecimalFormat) NumberFormat.getIntegerInstance();
        private DecimalFormat doubleFormat = (DecimalFormat) NumberFormat.getInstance();
        private long amount2trade = 0;
        private long amount2fix = 0;
        private long[] results = new long[3];
        private double[] ratios = new double[3];

        public void actionPerformed(ActionEvent ae) {
            readRatios();
            readAmountFields();
            switch (tradeType) {
                case ONE_RESOURCE_TRADE_TYPE:
                    tradeFree();
                    break;
                case FIXED_RESOURCE_TRADE_TYPE:
                    tradeFixed();
                    break;
            }
        }

        /**
         * Parses the double values in each input RatioFields
         */
        private void readRatios() {
            try {
                ratios[0] = doubleFormat.parse(metalRatioField.getText().replaceAll("\\.", ",")).doubleValue();
                ratios[1] = doubleFormat.parse(cristalRatioField.getText().replaceAll("\\.", ",")).doubleValue();
                ratios[2] = doubleFormat.parse(deuteriumRatioField.getText().replaceAll("\\.", ",")).doubleValue();
            } catch (ParseException ex) {
                ratios[0] = 3;
                ratios[1] = 2;
                ratios[2] = 1;
                Logger.getLogger(CCGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        /**
         * Parses the long values in each input amount JTextField
         */
        private void readAmountFields() {
            try {
                amount2trade = intFormat.parse(amount2TradeField.getText()).longValue();
                amount2fix = intFormat.parse(amount2FixField.getText()).longValue();
            } catch (ParseException parseException) {
            }
        }

        /**
         * Trades the specified amount in amount2tradeField with the specified
         * resource in fixedResourceBox fixed amount specified in amount2FixField.
         */
        private void tradeFixed() {
            final Trader trader = new Trader(res2trade, ratios);
            results = trader.tradeFixed(amount2trade, fixedResource, amount2fix);
            results[res2trade.ordinal()] = 0;
            results[fixedResource.ordinal()] = 0;
            showResults();
            writeSummaryFixed();
        }

        /**
         * Trades the specified amount in amount2TradeField in all resources,
         * no fixed resource is provided.
         */
        private void tradeFree() {
            Trader trader = new Trader(res2trade, ratios);
            results = trader.tradeSimple(amount2trade);
            results[res2trade.ordinal()] = 0;
            showResults();
            writeSummarySimple();
        }

        /**
         * Shows the result in a readable way, puts the results amount for each
         * resource in it's xxxOut JTextField.
         */
        private void showResults() {
            if (results[0] != 0) {
                metalOut.setText(intFormat.format(results[0]));
            } else {
                metalOut.setText("----");
            }
            if (results[1] != 0) {
                cristalOut.setText(intFormat.format(results[1]));
            } else {
                cristalOut.setText("----");
            }
            if (results[2] != 0) {
                deuteriumOut.setText(intFormat.format(results[2]));
            } else {
                deuteriumOut.setText("----");
            }
        }

        /**
         * Writes the summary of the entire transaction in the Output JTextArea.
         * This method gives the choice in the resource to be traded (no fixed
         * resource amount).
         */
        private void writeSummarySimple() {
            String s = "Cambiar " + res2trade.toString() + ": " + amount2TradeField.getText() + "\n"
                    + "por alguna de las siguientes opciones:\n\n";
            for (Resource r : Resource.values()) {
                long res = results[r.ordinal()];
                if (res != 0) {
                    s += "  * " + intFormat.format(res) + " unidades de " + r.toString() + "\n";
                }
            }
            summaryOutput.setText(s);
        }

        /**
         * Writes the summary of the entire transaction in the Output JTextArea.
         * This method gives the instruction in the package to be traded (fixed
         * resource amount and the remaining in the 3rd resource to be traded).
         */
        private void writeSummaryFixed() {
            String s = "Cambiar " + res2trade.toString() + ": " + intFormat.format(amount2trade) + "\n"
                    + "por todo lo siguiente:\n";
            s += "  * " + intFormat.format(amount2fix) + " unidades de " + fixedResource.toString() + "\n";
            for (Resource r : Resource.values()) {
                long res = results[r.ordinal()];
                if (res != 0) {
                    s += "  * " + intFormat.format(res) + " unidades de " + r.toString() + "\n";
                }
            }
            summaryOutput.setText(s);
        }
    }

    /**
     * Action that clears all input and output fields
     */
    private class CleanAction extends AbstractAction {

        public void actionPerformed(ActionEvent ae) {
            final JTextField[] jTextFields = {amount2TradeField,
                amount2FixField,
                metalOut, cristalOut, deuteriumOut};
            for (JTextField jTextField : jTextFields) {
                jTextField.setText("");
            }
        }
    }
}
